/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.manager.service.impl;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.exception.BizException;
import cc.iotkit.common.utils.MapstructUtils;
import cc.iotkit.data.manager.IMapFenceDevicesData;
import cc.iotkit.manager.dto.bo.map.MapFenceDevicesBo;
import cc.iotkit.manager.dto.vo.biz.BizWorkorderReplaceVo;
import cc.iotkit.manager.dto.vo.map.MapFenceDevicesVo;
import cc.iotkit.manager.service.IMapFenceDevicesService;
import cc.iotkit.manager.service.IMapService;
import cc.iotkit.model.biz.BizWorkorderReplace;
import cc.iotkit.model.map.MapFence;
import cc.iotkit.model.map.MapFenceDevices;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 租户Service业务层处理
 *
 * @author Michelle.Chung
 */
@RequiredArgsConstructor
@Service
public class MapFenceDevicesServiceImpl implements IMapFenceDevicesService {
    private final IMapService mapService;
    private final IMapFenceDevicesData sysMapFenceDevicesData;

    public MapFenceDevicesVo queryById(Long id) {
        return MapstructUtils.convert(sysMapFenceDevicesData.findById(id),MapFenceDevicesVo.class);
    }

    @Transactional
    public List<MapFenceDevicesVo> saveAll(List<MapFenceDevices> list, Long pid,Integer gfid){
        //获取原始数据
        MapFenceDevices cond=new MapFenceDevices();
        cond.setPid(pid);
        List<MapFenceDevices> oldList=sysMapFenceDevicesData.findAllByCondition(cond);

        //去除差异数据
        List<Long> oldIds=oldList.stream().map(item->item.getId()).collect(Collectors.toList());
        List<Long> newIds=list.stream().filter(m->m.getId()!=null).map(item->item.getId()).collect(Collectors.toList());
        Collection<Long> delIds = CollectionUtil.subtract(oldIds, newIds).stream().collect(Collectors.toList());
        if(delIds.size()>0)
            this.deleteByIds(delIds);

        //保存数据
        list.forEach(m->{
            m.setPid(pid);
            m.setGfid(gfid);
        });
        List<MapFenceDevicesVo> results=  MapstructUtils.copyListToList(sysMapFenceDevicesData.saveAll(list),MapFenceDevicesVo.class);

        //获取绑定的设备终端id字符串
        String tids=list.stream().map(m->m.getAmapTid()).collect(Collectors.joining(","));
        //删除围栏绑定的设备
        mapService.bindFenceTerminal(gfid,tids);

        return results;
    }

    /**
     * 新增保存角色信息
     *
     * @param bo 角色信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(MapFenceDevicesBo bo) {
        //sysMapFenceDevicesData.save(bo.to(MapFenceDevices.class));
        try {
            if (bo.getId() == null) {
                if (mapService.bindFenceTerminal(bo.getGfid(),bo.getAmapTid()));
                    sysMapFenceDevicesData.save(bo.to(MapFenceDevices.class));
            } else {
                 sysMapFenceDevicesData.save(bo.to(MapFenceDevices.class));
            }
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }
        return true;
    }

    @Override
    public boolean deleteById(Long id) {
        sysMapFenceDevicesData.deleteById(id);
        return true;
    }

    @Transactional
    public boolean deleteByIds(Collection<Long> ids) {
        try {
            List<MapFenceDevices> mapFences = sysMapFenceDevicesData.findByIds(ids);
            String tids = mapFences.stream().map(m -> m.getAmapTid().toString()).collect(Collectors.joining(", "));

            sysMapFenceDevicesData.deleteByIds(ids);
            mapService.unbindFenceTerminal(mapFences.get(0).getGfid(),tids);

            return true;
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }

    }

    @Transactional
    public boolean deleteByPids(Collection<Long> pids) {
        try {
            pids.forEach(pid->{
                MapFenceDevices cond=new MapFenceDevices();
                cond.setPid(pid);
                List<MapFenceDevices> list=sysMapFenceDevicesData.findAllByCondition(cond);

                //去除差异数据
                List<Long> ids=list.stream().map(item->item.getId()).collect(Collectors.toList());

                String tids = list.stream().map(m -> m.getAmapTid().toString()).collect(Collectors.joining(", "));

                sysMapFenceDevicesData.deleteByIds(ids);
                mapService.unbindFenceTerminal(list.get(0).getGfid(),tids);
            });

            return true;
        }catch (Exception e){
            throw new BizException(e.getMessage());
        }

    }

    @Override
    public Paging<MapFenceDevicesVo> queryPageList(PageRequest<MapFenceDevicesBo> request) {
        Paging<MapFenceDevices> pages=sysMapFenceDevicesData.findAllByConditions(request.to(MapFenceDevices.class));
        return pages.to(MapFenceDevicesVo.class);
    }

    @Override
    public List<MapFenceDevicesVo> queryList(MapFenceDevicesBo bo) {
        List<MapFenceDevices> list=sysMapFenceDevicesData.findAllByCondition(bo.to(MapFenceDevices.class));
        return MapstructUtils.copyListToList(list,MapFenceDevicesVo.class);
    }



}
